package com.wmh.baseservice.common.shiro.service;

import com.wmh.baseservice.common.shiro.bean.JwtToken;
import com.wmh.baseservice.common.utils.LogUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Date: 2021-10-29 17:31
 * @author xy
 * @describe 自定义jwtFilter过滤器
 */
public class JwtShiroFilter extends BasicHttpAuthenticationFilter {


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if ((httpRequest.getHeader("Authorization") != null)) {
            //executeLogin 方法执行登入，检查 token 是否正确，校验token
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                if (e.getMessage().contains("Submitted")) {
                    errorResponse(httpResponse, -1);
                } else {
                    errorResponse(httpResponse, 1);
                }
                return false;
            }
        } else {
            errorResponse(httpResponse, 1);
            return false;
        }
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("Authorization").replace("Bearer_", "");
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，错误会抛出异常
        getSubject(request, response).login(jwtToken);
        return true;
    }


    /**
     * 自定义返回
     */
    public void errorResponse(HttpServletResponse response, Integer type) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
            switch (type) {
                case 1:
                    response.getWriter().println(ReturnBody.error(ResultCodeInfo.TOKEN_EXPIRE));
                    break;
                case -1:
                    response.getWriter().println(ReturnBody.error(ResultCodeInfo.ACCOUNT_OR_PWD_ERROR));
            }
        } catch (IOException e) {
            LogUtil.error(e.getMessage());
        }
    }
}
